package com.donger.upms.biz.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.donger.upms.api.entity.SysDept;
import com.donger.upms.api.entity.SysDeptRelation;
import com.donger.upms.biz.mapper.SysDeptRelationMapper;
import com.donger.upms.api.service.ISysDeptRelationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysDeptRelationServiceImpl extends ServiceImpl<SysDeptRelationMapper, SysDeptRelation> implements ISysDeptRelationService {

    /**
     * 维护部门关系
     *
     * @param sysDept
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertDeptRelation(SysDept sysDept) {
        // 增加部门关系
        SysDeptRelation condition = new SysDeptRelation();
        condition.setDescendant(sysDept.getParentId());
        // 所有父节点 的祖先 增加该叶子节点

        List<SysDeptRelation> relationList = this.baseMapper.
                selectList(new LambdaQueryWrapper<SysDeptRelation>()
                        .eq(SysDeptRelation::getDescendant, sysDept.getParentId()))
                .stream().peek(relation -> relation.setDescendant(sysDept.getDeptId())).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(relationList)) {
            this.saveBatch(relationList);
        }
        //自己也要维护到关系表中
        SysDeptRelation own = new SysDeptRelation();
        own.setDescendant(sysDept.getDeptId());
        own.setAncestor(sysDept.getDeptId());
        this.baseMapper.insert(own);
    }

    @Override
    public void deleteAllDeptRealtion(Long id) {
        this.baseMapper.deleteDeptRelationsById(id);
    }

    @Override
    public void updateDeptRealtion(SysDeptRelation relation) {
        this.baseMapper.updateDeptRelations(relation);
    }
}
